const path = require('path');
const { Worker } = require('worker_threads');
const URL = require('../utils/url');
const Default_Xml = require("../utils/xml");
const { getTokenLoginCookie } = require('./login');
const { DEFAULT_XML, REPO_DIR } = require("../constant/index")
const shelljs = require('shelljs');
const os = require('os');

async function packBundle() {
    const [
        codeBranch = "master",
        version = "3.0.0-snapshot",
        loginUser = "8EBENJ2"
    ] = process.argv.slice(2)
    await getTokenLoginCookie(URL.login, { ignoreCache: true, loginUser });
    const default_xml = await Default_Xml.fromPath(DEFAULT_XML)
    shelljs.rm("-rf", path.resolve(REPO_DIR, "*"), { async: true })
    // const repoNames = default_xml.xmlData.map(item => item.name)
    // const repoNames = default_xml.xmlData.map(item => item.name).filter(name => name.startsWith('third_party_')).slice(5, 15)
    // console.log(repoNames);
    const repoNames = ["utils_native_lite"]
    const errlogs = []
    let workerCount = 0
    repoNames.forEach(repoName => {
        const worker = new Worker(path.resolve(__dirname, "..", "thread", "index.js"), {
            workerData: {
                repoName,
                version,
                destPath: default_xml.matchRepo(repoName),
                action: "pack",
                codeBranch
            }
        })
        worker.on("exit", exitCode => {
            workerCount++
            if (exitCode===0){

            }
            if (workerCount === repoNames.length) {
                console.log(errlogs.join(os.EOL));
            }
        })
        worker.on("message", log => {
            errlogs.push(log)
        })
    })
}

packBundle()